import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { getToken } from '@/utils/auth'

// 路由组件懒加载
const Login = () => import('@/views/Login/index.vue')

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: {
      title: '企业福利商城 - 登录',
      requiresAuth: false
    }
  },
  {
    path: '/home',
    name: 'Home',
    component: () => import('@/views/Home/index.vue'),
    meta: {
      title: '企业福利商城 - 首页',
      requiresAuth: true
    }
  },
  {
    path: '/dashboard',
    name: 'Dashboard',
    component: () => import('@/views/Dashboard/index.vue'),
    meta: {
      title: '工作台',
      requiresAuth: true
    }
  },
  {
    path: '/admin/dashboard',
    name: 'AdminDashboard',
    component: () => import('@/views/Admin/Dashboard/index.vue'),
    meta: {
      title: '管理员工作台',
      requiresAuth: true,
      roles: ['ROLE_ADMIN']
    }
  },
  {
    path: '/admin/employee',
    name: 'AdminEmployee',
    component: () => import('@/views/Admin/Employee/index.vue'),
    meta: {
      title: '员工管理',
      requiresAuth: true,
      roles: ['ROLE_ADMIN']
    }
  },
  {
    path: '/admin/product',
    name: 'AdminProduct',
    component: () => import('@/views/Admin/Product/index.vue'),
    meta: {
      title: '商品管理',
      requiresAuth: true,
      roles: ['ROLE_ADMIN']
    }
  },
  {
    path: '/admin/category',
    name: 'AdminCategory',
    component: () => import('@/views/Admin/Category/index.vue'),
    meta: {
      title: '分类管理',
      requiresAuth: true,
      roles: ['ROLE_ADMIN']
    }
  },
  {
    path: '/admin/welfare-card',
    name: 'AdminWelfareCard',
    component: () => import('@/views/Admin/WelfareCard/index.vue'),
    meta: {
      title: '福利卡管理',
      requiresAuth: true,
      roles: ['ROLE_ADMIN']
    }
  },
  {
    path: '/admin/order',
    name: 'AdminOrder',
    component: () => import('@/views/Admin/Order/index.vue'),
    meta: {
      title: '订单管理',
      requiresAuth: true,
      roles: ['ROLE_ADMIN']
    }
  },
  {
    path: '/admin/statistics',
    name: 'AdminStatistics',
    component: () => import('@/views/Admin/Statistics/index.vue'),
    meta: {
      title: '数据统计',
      requiresAuth: true,
      roles: ['ROLE_ADMIN']
    }
  },
  {
    path: '/profile',
    name: 'Profile',
    component: () => import('@/views/Profile/index.vue'),
    meta: {
      title: '个人信息',
      requiresAuth: true
    }
  },
  {
    path: '/card-exchange',
    name: 'CardExchange',
    component: () => import('@/views/WelfareCardExchange/index.vue'),
    meta: {
      title: '福利卡兑换',
      requiresAuth: true
    }
  },
  {
    path: '/products',
    name: 'ProductList',
    component: () => import('@/views/Product/List.vue'),
    meta: {
      title: '商品列表',
      requiresAuth: true
    }
  },
  {
    path: '/product/:id',
    name: 'ProductDetail',
    component: () => import('@/views/Product/Detail.vue'),
    meta: {
      title: '商品详情',
      requiresAuth: true
    }
  },
  {
    path: '/categories',
    name: 'CategoryList',
    component: () => import('@/views/Category/List.vue'),
    meta: {
      title: '商品分类',
      requiresAuth: true
    }
  },
  {
    path: '/category/:id',
    name: 'CategoryDetail',
    component: () => import('@/views/Category/Detail.vue'),
    meta: {
      title: '分类详情',
      requiresAuth: true
    }
  },
  {
    path: '/favorites',
    name: 'FavoriteList',
    component: () => import('@/views/Favorite/List.vue'),
    meta: {
      title: '我的收藏',
      requiresAuth: true
    }
  },
  {
    path: '/cart',
    name: 'Cart',
    component: () => import('@/views/Cart/index.vue'),
    meta: {
      title: '购物车',
      requiresAuth: true
    }
  },
  {
    path: '/order/checkout',
    name: 'OrderCheckout',
    component: () => import('@/views/Order/Checkout.vue'),
    meta: {
      title: '订单结算',
      requiresAuth: true
    }
  },
  {
    path: '/order/list',
    name: 'OrderList',
    component: () => import('@/views/Order/List.vue'),
    meta: {
      title: '我的订单',
      requiresAuth: true
    }
  },
  {
    path: '/order/:id',
    name: 'OrderDetail',
    component: () => import('@/views/Order/Detail.vue'),
    meta: {
      title: '订单详情',
      requiresAuth: true
    }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  // 设置页面标题
  if (to.meta.title) {
    document.title = to.meta.title
  }

  // 获取用户状态
  const userStore = useUserStore()
  const hasToken = getToken()

  // 如果有token但是没有用户信息，尝试获取用户信息
  if (hasToken && !userStore.userInfo) {
    try {
      await userStore.getUserInfo()
    } catch (error) {
      console.error('获取用户信息失败:', error)
      // 如果获取用户信息失败，清除token并跳转到登录页
      userStore.resetState()
      next('/login')
      return
    }
  }

  // 不需要认证的页面直接放行
  if (!to.meta.requiresAuth) {
    // 如果已登录且访问登录页，重定向到首页
    if (hasToken && to.path === '/login') {
      // 根据用户角色跳转到不同的首页
      if (userStore.isAdmin) {
        next('/admin/dashboard')
      } else {
        next('/home')
      }
    } else {
      next()
    }
    return
  }

  // 需要认证的页面
  if (!hasToken) {
    // 没有token，重定向到登录页
    next('/login')
    return
  }

  // 检查角色权限
  if (to.meta.roles) {
    const hasRole = userStore.getUserRoles.some(role =>
      to.meta.roles.includes(role.roleCode)
    )
    if (!hasRole) {
      // 权限不足，重定向到首页
      if (userStore.isAdmin) {
        next('/admin/dashboard')
      } else {
        next('/home')
      }
      return
    }
  }

  next()
})

export default router